package com.weixin.service;

import com.weixin.pojo.WXMsg;
import com.weixin.util.MyWXPayConfig;
import com.weixin.util.WXUserUtil;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import com.weixin.wxpay.sdk.WXPayConstants;
import com.weixin.wxpay.sdk.WXPayRequest;
import com.weixin.wxpay.sdk.WXPayUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;


@Service("weixinNotifyService")
public class WeixinNotifyService {

    public void sendMsg(WXMsg wxMsg,String secret)throws Exception{
        JSONObject jsonObject = JSONObject.fromObject(wxMsg);
        String accessToken = WXUtil.getToken(WxepConstants.CorpId,secret);
        String url = WxepConstants.SEND_MSG_URL.replace("{accessToken}",accessToken);
        WXUtil.httpRequest(url,"POST",jsonObject.toString());
    }

    public boolean sendRedPack(String userId)throws Exception{
        Map<String, String> requestData = fillRequestData(userId);
        String sendStr = WXPayUtil.generateSignedXml(requestData, WxepConstants.WX_PAY_SECRET);
        WXPayRequest wxPayRequest = new WXPayRequest(new MyWXPayConfig());
        try{
            String responseStr = wxPayRequest.requestWithCert(WxepConstants.REDPACK_URL_SUFFIX, requestData.get("nonce_str"), sendStr, true);
            return processResponseXml(responseStr);
        }catch (Exception e){
            throw e;
        }
    }

    public Map<String,String>  fillRequestData(String userId) throws Exception{
        Map<String, String> sendData = new HashMap<>();
        String openId = WXUserUtil.convertToOpenid(userId); //openid
        String nonce_str = WXPayUtil.generateNonceStr(); // 随机数
        String mch_billno = WxepConstants.MCH_ID+ WXUtil.gengertorBillno();// 订单号
        String act_name = "评价有奖活动";
        int total_amount = WXUtil.gengertorAmount(); //金额
        sendData.put("act_name",act_name);
        sendData.put("mch_billno",mch_billno);
        sendData.put("mch_id",WxepConstants.MCH_ID);
        sendData.put("nonce_str",nonce_str);
        sendData.put("re_openid",openId);
        sendData.put("total_amount",total_amount+"");
        sendData.put("wxappid",WxepConstants.CorpId);
        String workwx_sign = WXPayUtil.generateSignature(sendData, WxepConstants.WORKWX_PAY_SECRET);//企业微信签名
        sendData.put("workwx_sign",workwx_sign);
        sendData.put("wishing",WxepConstants.WISHING);// 红包祝福语
        sendData.put("remark",WxepConstants.REMARK);// 备注
        return sendData;
    }


    /**
     * 处理 HTTPS API返回数据，转换成Map对象。return_code为SUCCESS时，验证签名。
     * @param xmlStr API返回的XML格式数据
     * @return Map类型数据
     * @throws Exception
     */
    public boolean processResponseXml(String xmlStr) throws Exception {
        String return_code;
        Map<String, String> respData = WXPayUtil.xmlToMap(xmlStr);
        if (respData.containsKey(WXPayConstants.RETURN_CODE)) {
            return_code = respData.get(WXPayConstants.RETURN_CODE);
        }
        else {
            throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
        }

        if (return_code.equals(WXPayConstants.FAIL)) {
            return false;
        }
        else if (return_code.equals(WXPayConstants.SUCCESS)) {
            if (this.isResponseSignatureValid(respData)) {
                return true;
            }
            else {
                throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
            }
        }
        else {
            throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
        }
    }

    /**
     * 判断xml数据的sign是否有效，必须包含sign字段，否则返回false。
     *
     * @param reqData 向wxpay post的请求数据
     * @return 签名是否有效
     * @throws Exception
     */
    public boolean isResponseSignatureValid(Map<String, String> reqData) throws Exception {
        // 返回数据的签名方式和请求中给定的签名方式是一致的
        return WXPayUtil.isSignatureValid(reqData, WxepConstants.WX_PAY_SECRET, WXPayConstants.SignType.MD5);
    }
}